package com.ygxsk.carhome.ui.usercenter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.mbms.DownloadRequest;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eralp.circleprogressview.CircleProgressView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.tencent.mmkv.MMKV;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebHistoryItem;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.dsbridge.CompletionHandler;
import com.ygxsk.carhome.dsbridge.DWebView;
import com.ygxsk.carhome.event.EventBusQRCode;
import com.ygxsk.carhome.event.EventSignatureDetail;
import com.ygxsk.carhome.event.EventSignatureMain;
import com.ygxsk.carhome.js.JsApi;
import com.ygxsk.carhome.js.JsApiListener;
import com.ygxsk.carhome.js.MJavascriptInterface;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.MianTaskManager;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.SignatureWebBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxMiddleTitle;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.zxing.MyBGAQRCodeActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.ViewUitls;
import com.ygxsk.carhome.views.ProgressView;
import com.ygxsk.integrated.retrofit.Parameterkey;
import com.zxy.tiny.Tiny;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-02-21  17:13
 * @Description:普通的正常的webView内容 携带标记内容过来，
 */
public class WebViewDetailActivity extends ErrorActivity implements View.OnTouchListener {

    interface PicChooseCallback {

        void clickCamera(int position);

        void clickAlbum(int position, int remainNum);

    }

    //页面顶部标题的记忆记录问题
    private HashMap<String, String> hashMapTitle = new HashMap<>();

    private String titleName = "";

    private DownloadRequest mRequest;

    /**
     * 监听区分该界面的标识内容
     */
    private final int RXBUS_MIDDLETITLE = 15;

    //加载方式的携带->1：社区动态 2：帮助中心
    //该界面暂时所有的判断都是根据这个值判断的。
    private int webViewFlag = 0;

    /**
     * 填充携带的数字编号
     */
//    private int extraCode;

    /**
     * 从别的界面例如团购商品，家具，家装的结算界面-webView的跳出去标志
     */
    private String webViewFlagBack = "";

    /**
     * 添加从结算进来的添加地址的标识,用于在返回或者关闭时候提交刷新结算的地址id.
     */
    private final String webViewFlagBackAccount = "";

    @BindView(R.id.framelayoutwebviedetail)
    FrameLayout frameLayoutWebViewDetail;

    /**
     * 下载图片的进度圈内容
     */
//    MaterialProgressBar materialProgressBar;
    //加载页面的进度圈圈
    @BindView(R.id.circle_progress_view)
    CircleProgressView mCircleProgressView;

    //添加view内容，使用携带桥接的自定义webview
//    private WebView mWebView;
    private DWebView mWebView;

    private Session mSession;

    private Tiny.FileCompressOptions compressOptions;

    /**
     * 判断网页是否加载完全,默认是false
     */
    private boolean loadError = false;

    private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    private ToolbarHelper toolbarHandler;
    //====================================================
    /**
     * 跳转的标识内容，主要是用于从物业缴费成功的界面过来然后返回到首页的逻辑
     */
    private int jumpFromFlag;

    //==========================================================================
    private PermissionSetting mSetting;

    /**
     * 该界面的弹窗内容
     */
//    private AlertView mAlertView;

    //处理主页的内容
    private final int HANDLER_NOMAL_FLAG = 202;
    //处理扫描出来的二维码链接的标识
    private final int HANDLER_QCODE_FLAG = 2022;
    //更新进度条的标识
    private final int HANDLER_PROGRESS_FLAG = 2122;

    //是从首页携带过来的外链的地址
    private final int HANDLER_EXTRA_WEBVIEW_LOADURL = 2125;

    //2022-8-9 15:13:50 新增关于隐私政策的
    private final int HANDLER_TEXTURL_PRIVACY_POLICY = 2123;
    //2022-8-9 15:14:44 新增的关于用户协议的内容
    private final int HANDLER_TEXTURL_USER_AGREEMENT = 2124;


    //打开企业认证，刚认证的结果响应给手机端
    private final int HANDLER_ADD_COMPANY_SIGNATURE_CALLBACK = 2126;

    //设置自动滚动到顶部，主要为了H5处理一个事件做返回用。
    private final int HANDLER_SCROLLTO_TOP = 2127;

    //处理相机类的，因为有权限判断，需要放在主线程
    private final int HANDLER_CAMERA_ALBUM_VIDEO = 2128;

    //新打开一个webView
    private final int HANDLER_OPEN_NEW_WEB = 2129;

    //添加toolbar的返回
//    private final int HANDLER_TOOLBAR_BACKORREFRESH = 2130;
    //执行扫描 一维码或者二维码 跳转activity的能力
//    private final int HANDLER_QRCODE_JUMP_SCANACTIVITY = 2131;

//    private PicChooseCallback picChooseCallback = new PicChooseCallback() {
//        @Override
//        public void clickCamera(int position) {
//
//            //调用相机拍照
//            Album.camera(WebViewDetailActivity.this)
//                    .image()//
//                    .filePath(PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.STARTWITH_WEB_SIGNATURE_FLAG + TimeUtils.getNowMills() + ".jpg")//
//                    .onResult(new Action<String>() {//
//                        @Override
//                        public void onAction(@NonNull String result) {
//
//                            //拍照路径内容
//                            //Glide展示内容
//                            //图片裁剪，这里暂时不裁剪。
//                            //LogUtils.d("itchen----相机拍摄的路径--->" + result);
//                            //2020年8月29日11:29:42 重新修改
//                            //itchen----相机拍摄的路径--->/storage/emulated/0/Android/data/com.dgj.propertyred/files/repair1598671747262.jpg
//                            //takePicture(result);
//                            fillImagesLogic(result);
//
//                        }
//
//                    }).onCancel(new Action<String>() {
//                        @Override
//                        public void onAction(@NonNull String result) {
//                            //CommUtils.displayToastShort(WebViewDetailActivity.this, getResources().getString(R.string.camera_cancel));
//                            ToastUtils.showShort(getResources().getString(R.string.camera_cancel));
//                        }
//                    }).start();
//
//        }
//
//        @Override
//        public void clickAlbum(int position, final int _remainNum) {
//
//            if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)//
//                    || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
//                    || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//
//
//                CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
//                    @Override
//                    public void doSomeThing() {
//                        //添加访问权限内容
//                        AndPermission.with(WebViewDetailActivity.this)
//                                .runtime()//
//                                .permission(Permission.READ_EXTERNAL_STORAGE, //
//                                        Permission.WRITE_EXTERNAL_STORAGE,//
//                                        Permission.CAMERA)//
//                                .rationale(new RuntimeRationale())//
//                                .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
//                                    @Override
//                                    public void onAction(List<String> permissions) {
//
//                                        clickAlum(_remainNum);
//
//                                    }
//                                }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
//                                    @Override
//                                    public void onAction(List<String> permissions) {
//
//                                        ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);
//
//                                        if (AndPermission.hasAlwaysDeniedPermission(WebViewDetailActivity.this, permissions)) {
//                                            mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, WebViewDetailActivity.this, permissions);
//                                        }
//
//                                    }
//                                }).start();
//
//                    }
//                });
//
//            } else {
//
//                clickAlum(_remainNum);
//
//            }
//
//
//        }
//    };

    //===============================================================================================================
//    public void clickAlum(int _remainNum) {
//
//        //从相册里选择图片
//        //调用相册选择
//        //调用相册选择
//        Album.image(WebViewDetailActivity.this)
//                .multipleChoice()//可以多选
//                //.singleChoice()//
//                .camera(true)//
//                .columnCount(2)//
//                .selectCount(_remainNum + 1)//最多只能选择1张照片.不然导致我的相册出bug.这里需要重新整改。
//                //.checkedList(mAlbumFiles)//多选的时候避免重复选择
//                .widget(Widget.newLightBuilder(WebViewDetailActivity.this)//自定义的界面可以不要
//                        .title("选择图库")//
//                        .statusBarColor(Color.WHITE)//状态栏颜色。
//                        .toolBarColor(Color.WHITE)//Toolbar颜色。
//                        .mediaItemCheckSelector(Color.BLUE, Color.RED)//图片或者视频选择框的选择器。
//                        .bucketItemCheckSelector(Color.BLUE, Color.WHITE)//切换文件夹时文件夹选择框的选择器
//                        .buttonStyle(Widget.ButtonStyle.newLightBuilder(WebViewDetailActivity.this)//
//                                .setButtonSelector(Color.BLUE, Color.WHITE)//
//                                .build()).build())//
//
//                .onResult(new Action<ArrayList<AlbumFile>>() {
//                    @Override
//                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
//
//
//                        //2018/11/30 原始代码发现该处并没用到
//                        //mAlbumFiles = result;
//
//                        /*ArrayList<String> pathStringList = new ArrayList<>();
//                        for (AlbumFile albumFile:result) {
//                            pathStringList.add(albumFile.getPath());
//                        }
//                        takePicture(pathStringList);//图片路径内容
//                        */
//                        //==========================================================================
//                        //这个列表 要单独划开，因为上传的时候 要整体上传的。
//                        // 准备采用。图片压缩。
//
//                        //2018年03月14日。原始代码。
//                        for (int index = 0; index < result.size(); index++) {
//
//                            fillImagesLogic(result.get(index).getPath());
//                            //LogUtils.d("itchen----->" + result.get(index).getPath());
//
//                        }
//
//                    }
//
//                })
//                .onCancel(new Action<String>() {
//                    @Override
//                    public void onAction(@NonNull String result) {
//                        ToastUtils.showShort("取消了");
//                    }
//
//                })
//                .start();
//
//    }


//    private void fillImagesLogic(final String _imagePath) {
//
//        Tiny.getInstance().source(_imagePath).asFile().withOptions(compressOptions).compress(new FileCallback() {
//
//            @Override
//            public void callback(boolean isSuccess, String outfile, Throwable t) {
//
//                if (!isSuccess) {//压缩失败就上传原图即可。
//                    //LogUtils.d("itchen--有压缩失败-" + t.getMessage());
//                    //return;
//
//                    ImageBean imageBean = new ImageBean(_imagePath);
//
//                    if (it_picker_view != null) {
//                        it_picker_view.addData(imageBean);
//                    }
//
//                    uploadImageListPass.add(imageBean);
//
//
//                } else {//图片压缩成功，上传压缩图
//
//                    //File file = new File(outfile);
//                    //setupCompressInfo(outfile, file.length());
//                    //LogUtils.d("itchen---图片压缩成功=>"+outfile);
//                    //itchen---图片压缩成功=>/storage/emulated/0/Android/data/com.dgj.propertyowner/tiny/tiny-40-2018-04-04-14-05-45.jpg
//                    ImageBean imageBean = new ImageBean(outfile);
//                    if (it_picker_view != null) {
//                        it_picker_view.addData(imageBean);
//                    }
//                    uploadImageListPass.add(imageBean);
//
//                }
//
//            }
//        });
//
//
//        //原始未添加压缩的图片代码
//        /*ImageBean imageBean = new ImageBean(imagePath);
//        it_picker_vi.addData(imageBean);
//        uploadImageListPass.add(imageBean);*/
//    }

    private final Handler handlerNomal = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case HANDLER_ADD_COMPANY_SIGNATURE_CALLBACK: {

                    SignatureWebBean signatureWebBean = (SignatureWebBean) msg.obj;

                    // 状态值//1是成功，2是失败
                    if (signatureWebBean != null) {

                        int status = signatureWebBean.get_status();
                        String message = signatureWebBean.getMsg();

                        if (status == 1) {

                            //消息接收成功，那么关闭该界面传递
                            if (!TextUtils.isEmpty(message)) {
                                PopTip.show(message).iconSuccess();
                            } else {
                                PopTip.show(getResources().getString(R.string.web_receive_successed)).iconSuccess();
                            }

                            //通知档案的两个列表刷新
                            //单独的刷新 该合同详情主页
                            EventSignatureDetail eventSignatureDetail = new EventSignatureDetail();
                            eventSignatureDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_SIGNATURE_DETAIL);
                            EventBus.getDefault().post(eventSignatureDetail);

                            //单独的刷新 档案盒子主页列表
                            EventSignatureMain eventSignatureMainList = new EventSignatureMain();
                            eventSignatureMainList.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_SIGNATURE_MAIN_LIST);
                            EventBus.getDefault().post(eventSignatureMainList);

                            //消息接收成功，关闭activity
                            methodBack();

                        } else if (status == 2) {

                            //消息接收失败
                            if (!TextUtils.isEmpty(message)) {
                                PopTip.show(message).iconError();
                            } else {
                                PopTip.show(getResources().getString(R.string.web_receive_failed)).iconError();
                            }

                            EventSignatureDetail eventSignatureDetail = new EventSignatureDetail();
                            eventSignatureDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_SIGNATURE_DETAIL);
                            EventBus.getDefault().post(eventSignatureDetail);

                            //单独的刷新 档案盒子主页列表
                            EventSignatureMain eventSignatureMainList = new EventSignatureMain();
                            eventSignatureMainList.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_SIGNATURE_MAIN_LIST);
                            EventBus.getDefault().post(eventSignatureMainList);

                        }

                        LogUtils.json(ConstantSign.LOGCAT_NOMAL, signatureWebBean);
                    }

                    break;
                }

                case HANDLER_EXTRA_WEBVIEW_LOADURL: {

                    if (!TextUtils.isEmpty((String) msg.obj)) {

                        if (mWebView != null) {

                            mWebView.loadUrl((String) msg.obj);

                            /*mWebView.post(new Runnable() {
                                @Override
                                public void run() {
                                    mWebView.loadUrl((String)msg.obj);
                                }
                            });*/

                        }

                    } else {

                        netWorkError();
                    }

                    break;
                }

                case HANDLER_TEXTURL_USER_AGREEMENT: {//针对用户协议的加载

                    //貌似看过几个博客都是这个写在监听器之前.
                    if (!TextUtils.isEmpty((String) msg.obj)) {

                        if (mWebView != null) {

                            mWebView.loadUrl((String) msg.obj);

                            /*mWebView.post(new Runnable() {
                                @Override
                                public void run() {
                                    mWebView.loadUrl((String)msg.obj);
                                }
                            });*/

                        }

                    } else {

                        netWorkError();
                    }

                    break;
                }

                case HANDLER_TEXTURL_PRIVACY_POLICY: {//针对隐私政策的加载

                    //貌似看过几个博客都是这个写在监听器之前.
                    if (!TextUtils.isEmpty((String) msg.obj)) {

                        if (mWebView != null) {

                            mWebView.loadUrl((String) msg.obj);

                            /*mWebView.post(new Runnable() {
                                @Override
                                public void run() {
                                    mWebView.loadUrl((String)msg.obj);
                                }
                            });*/
                        }

                    } else {

                        netWorkError();
                    }

                    break;
                }

                case HANDLER_NOMAL_FLAG: {

                    //貌似看过几个博客都是这个写在监听器之前.
                    if (!TextUtils.isEmpty((String) msg.obj)) {

                        if (mWebView != null) {
                            mWebView.loadUrl((String) msg.obj);
                        }

                    } else {

                        netWorkError();
                    }

                    break;
                }

                case HANDLER_QCODE_FLAG: {

                    String codeResult = (String) msg.obj;

                    if (ActivityUtils.isActivityAlive(WebViewDetailActivity.this)) {

                        new MaterialDialog.Builder(WebViewDetailActivity.this)
                                .title("扫描结果")//
                                .content("该链接将跳转到外部页面：" + "\r\n" + codeResult)//
                                .positiveText("打开链接")//
                                .negativeText("关闭")//
                                .neutralText("复制链接")//
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                        //弹窗其实是否打开链接
                                        final Intent intent = new Intent();
                                        intent.setAction(Intent.ACTION_VIEW);
                                        intent.setData(Uri.parse(codeResult));

                                        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
                                        // 官方解释 : Name of the component implementing an activity that can display the intent
                                        if (intent.resolveActivity(getPackageManager()) != null) {

                                            final ComponentName componentName = intent.resolveActivity(getPackageManager());
                                            // 打印Log   ComponentName到底是什么
                                            //Log.e(TAG, "componentName = " + componentName.getClassName());
                                            startActivity(Intent.createChooser(intent, "请选择浏览器"));

                                        } else {
                                            ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
                                            ToastUtils.showShort("没有匹配的程序打开该链接~");
                                        }

                                    }
                                })
                                .onNeutral(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                        //复制到剪切板的内容。
                                        //LogUtils.d("复制到剪切板");
                                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 将文本内容放到系统剪贴板里。
                                        ClipData clipData = ClipData.newPlainText("newPlainTextLabel", codeResult);
                                        cm.setPrimaryClip(clipData);

                                        //CommUtils.displayToastLong(WebViewNormalActivity.this, "复制成功~");
                                        ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
                                        ToastUtils.showShort("复制成功~");

                                    }
                                })
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        //LogUtils.d("关闭弹窗");
                                    }
                                })
                                .cancelable(true)//
                                .show();//
                    }

                    break;
                }

                case HANDLER_PROGRESS_FLAG: {

                    if ((int) msg.obj == 100) {

                        if (mCircleProgressView != null) {
                            mCircleProgressView.setVisibility(View.GONE);
                        }

                        //加载完毕进度条消失
                        if (progressView != null) {
                            progressView.setVisibility(View.GONE);
                        }
                    } else {

                        //更新进度
                        if (mCircleProgressView != null) {
                            mCircleProgressView.setProgress((int) msg.obj);
                        }

                        //更新进度
                        if (progressView != null) {
                            progressView.setVisibility(View.VISIBLE);
                            progressView.setProgress((int) msg.obj);
                        }
                    }

                    break;
                }

                case HANDLER_OPEN_NEW_WEB: {//打开一个新的webview

                    String urlAddress = (String) msg.obj;
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--urlAddress-->" + urlAddress);
//                    ViewUitls.method_toWebView_OpenNew(urlAddress);

                    break;
                }

                default:
                    break;
            }
        }
    };

//    @OnClick({R.id.toolbar_layoutbackinweb})//点击关闭内容
//    public void ClickInWebDetail(View view) {
//
//        switch (view.getId()) {
//
//            case R.id.toolbar_layoutbackinweb: {
//                methodBack();
//                break;
//            }
//
//            default:
//                break;
//        }
//
//    }

    private MyJsApiListener myJsApiListener;

    /*
     * @Author:itchenqi175@163.com
     * @Time:2023-10-21  10:57
     * @Description:是添加
     */
    private class MyJsApiListener implements JsApiListener {

        @Override
        public void signatureCallback(SignatureWebBean signatureWebBean, CompletionHandler<String> handler) {

            sendMsg(handlerNomal, HANDLER_ADD_COMPANY_SIGNATURE_CALLBACK, signatureWebBean);

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "onCreate---onCreate---onCreate--onCreate--onCreate");

        mActivityInstance = this;

        MianTaskManager.getInstance(this).pushOneActivity(new WeakReference<Activity>(this));

        if (hashMapTitle == null) {
            hashMapTitle = new HashMap<>();
        }

        myJsApiListener = new MyJsApiListener();

//      myJsApiListener = new MyJsApiListener(toolbarHandler);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        //顶部可以写Rxjava内容传递消息内容
//        mSession = Session.get(this);
//        mSession.setPushToBulletinWebview(false);//做逻辑加强

        initloading();

        //rxbus
        initViews();

        processExtraData();

        //RxBus监听标题内容
        mCompositeDisposable.add(RxBus.getInstance().toObserverable(RxMiddleTitle.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxMiddleTitle>() {
                    @Override
                    public void accept(RxMiddleTitle rxMiddleTitle) throws Exception {

                        if (rxMiddleTitle != null) {

                            if (rxMiddleTitle.getMessage() == RXBUS_MIDDLETITLE) {

                                if (toolbarHandler != null) {

                                    if (!TextUtils.isEmpty(rxMiddleTitle.getContentString())) {
                                        toolbarHandler.setTitle(rxMiddleTitle.getContentString());
                                    } else {
                                        toolbarHandler.setTitle("");
                                    }

                                }
                            }
                        }
                    }
                }));


        mSetting = new PermissionSetting(this);

        //做图片压缩的配置。
        compressOptions = new Tiny.FileCompressOptions();
        compressOptions.config = Bitmap.Config.ARGB_8888;
        //compressOptions.quality=100; 这里可以设置压缩比例。

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }


    @Override
    protected void onStart() {
        super.onStart();

        // -----------location config -----------------------------------------------------
        //method_locOption();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    private void findWebView() {

        if (mWebView != null) {

            mWebView.setWebViewClient(new WebViewClient() {

                /*@Override
                public void onLoadResource(WebView webView, String s) {
                    LogUtils.d("itchen--url变化->"+s);
                    //这里会加载所有的资源
                    super.onLoadResource(webView, s);
                }*/

                @Override
                public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {

                    sslErrorHandler.proceed();// 接受所有网站的证书
                    //LogUtils.d("itchen--监听失败->");

                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--shouldOverrideUrlLoading-->" + url);
                    if (Build.VERSION.SDK_INT < 26) {
                        if (!TextUtils.isEmpty(url)) {
                            view.loadUrl(url);
                        } else {
                            netWorkError();
                        }
                        return true;
                    } else {
                        return false;
                    }
                }

                @Override
                public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                    super.onPageStarted(webView, s, bitmap);

                    mWebView.getSettings().setBlockNetworkImage(false);
                    //这里可以不要
                    /*if (loadingeasyInWebNomal != null) {
                        loadingeasyInWebNomal.showLoading();
                    }*/

//                    LogUtils.d("itchen--界面加载开始--onPageStarted--->" + s);

                }

                @Override
                public void doUpdateVisitedHistory(WebView webView, String s, boolean b) {
                    super.doUpdateVisitedHistory(webView, s, b);
                    //LogUtils.d("itchen----doUpdateVisitedHistory地址==" + s);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);

                    //LogUtils.d("itchen--界面加载完成--onPageFinished--->" + url);
                    mWebView.getSettings().setBlockNetworkImage(false);

                    //------------------------------------------------------------------
                    //------------------------------------------------------------------

                    loadingGone();

                    // android 6.0 以下通过title获取
                    ///当网页加载成功的时候判断是否加载成功
                    if (!loadError) {
                        //LogUtils.d("itchen--onPageFinished-网页加载成功");
                        loadingGone();
                        //itchen 加载的那个测试链接
                        //view.loadUrl(String.format(Locale.CHINA, "javascript:document.body.style.paddingTop='%fpx'; void 0", DensityUtil.px2dp(mWebView.getPaddingTop())));
                    } else {//网页加载失败。
                        //LogUtils.d("itchen--onPageFinished-网页加载失败！！！");
                        netWorkError();
                    }
                }
            });

            //Android6.0以下判断404或者500：
            mWebView.setWebChromeClient(webChromeClient);
        }

    }

    //5.0以下使用
    private ValueCallback<Uri> uploadMessage;
    // 5.0及以上使用
    private ValueCallback<Uri[]> uploadMessageAboveL;

    private WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView webView, int newProgress) {

            //LogUtils.d("itchen--->加载进度-->" + newProgress);

            if (handlerNomal != null) {
                sendMsg(handlerNomal, HANDLER_PROGRESS_FLAG, newProgress);
            }

            super.onProgressChanged(webView, newProgress);

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--onReceivedTitle-->" + title);

//            if (webViewFlag == ConstantApi.VALUE_JUMPFROM_SUGGESTIONS_MAINPAGE) {
//                if (!TextUtils.isEmpty(title)) {
//                    LogUtils.d("itchen--webView--title->" + title);
//                    RxBus.getInstance().post(new RxMiddleTitle(RXBUS_MIDDLETITLE, title));
//                } else {
//                    RxBus.getInstance().post(new RxMiddleTitle(RXBUS_MIDDLETITLE, titleName));
//                }

            if (!TextUtils.isEmpty(title)) {
                //记录标题，在返回时候做响应；
                if (hashMapTitle != null) {
                    hashMapTitle.put(view.getUrl(), title);
                }
//                LogUtils.json("itchen--存入本地的标题对应map是-->", hashMapTitle);
                RxBus.getInstance().post(new RxMiddleTitle(RXBUS_MIDDLETITLE, title));
            }
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }

//        //选择文件
//        // For Android < 3.0
//        public void openFileChooser(ValueCallback<Uri> valueCallback) {
//            mUploadCallBack = valueCallback;
//            showFileChooser();
//        }
//
//        // For Android  >= 3.0
//        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
//            mUploadCallBack = valueCallback;
//            showFileChooser();
//        }
//
//        //For Android  >= 4.1
//        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
//            mUploadCallBack = valueCallback;
//            showFileChooser();
//        }
//
//        // For Android >= 5.0
//        @Override
//        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
//            mUploadCallBackAboveL = filePathCallback;
//            showFileChooser();
//            return true;
//        }

    };


    String mCameraFilePath;

    private static final int REQUEST_CODE_FILE_CHOOSER = 2001;
    //图片
    private final static int FILE_CHOOSER_RESULT_CODE = 128;
    //拍照
    private final static int FILE_CAMERA_RESULT_CODE = 129;
    //拍照图片路径
    private String cameraFielPath;

    //电子签约的-选择营业执照的逻辑，在webview之中选择图片传递给webview
    private void openImageChooserActivity() {

        new MaterialDialog.Builder(this)
                .items(R.array.photo)
                .positiveText(getString(R.string.submitchangeinasset))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        if (uploadMessageAboveL != null) {
                            uploadMessageAboveL.onReceiveValue(null);
                            uploadMessageAboveL = null;
                        }

                        if (uploadMessage != null) {
                            uploadMessage.onReceiveValue(null);
                            uploadMessage = null;
                        }

                        dialog.dismiss();
                    }
                })
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {

                        if (position == 0) {

                            //android13小于的逻辑
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                //添加相机权限的改造
                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //添加访问权限内容
                                            AndPermission.with(WebViewDetailActivity.this)
                                                    .runtime()//
                                                    .permission(Permission.READ_EXTERNAL_STORAGE, //
                                                            Permission.WRITE_EXTERNAL_STORAGE,//
                                                            Permission.CAMERA)//
                                                    .rationale(new RuntimeRationale())//
                                                    .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            takeCamera();
//        }
                                                        }
                                                    }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);

                                                            if (AndPermission.hasAlwaysDeniedPermission(WebViewDetailActivity.this, permissions)) {
                                                                mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, WebViewDetailActivity.this, permissions);
                                                            }

                                                        }
                                                    }).start();

                                        }
                                    });

                                } else {
                                    takeCamera();
                                }

                            } else {

                                //android大于13版本
                                if (!XXPermissions.isGranted(WebViewDetailActivity.this, com.hjq.permissions.Permission.CAMERA)
                                        || !XXPermissions.isGranted(WebViewDetailActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {

                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            XXPermissions.with(WebViewDetailActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
//                                             .permission(com.hjq.permissions.Permission.)//
                                                    .permission(com.hjq.permissions.Permission.CAMERA)//
                                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
                                                    .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(WebViewDetailActivity.this, permissions)));

                                                            takeCamera();

                                                        }
                                                    });

                                        }
                                    });

                                } else {
                                    takeCamera();
                                }

                            }

                        } else if (position == 1) {

                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                                        || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //添加访问权限内容
                                            AndPermission.with(WebViewDetailActivity.this)
                                                    .runtime()//
                                                    .permission(Permission.READ_EXTERNAL_STORAGE, //
                                                            Permission.WRITE_EXTERNAL_STORAGE,//
                                                            Permission.CAMERA)//
                                                    .rationale(new RuntimeRationale())//
                                                    .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            takePhoto();

                                                        }
                                                    }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);

                                                            if (AndPermission.hasAlwaysDeniedPermission(WebViewDetailActivity.this, permissions)) {
                                                                mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, WebViewDetailActivity.this, permissions);
                                                            }

                                                        }
                                                    }).start();

                                        }
                                    });

                                } else {

                                    takePhoto();

                                }


                            } else {

                                if (!XXPermissions.isGranted(WebViewDetailActivity.this, com.hjq.permissions.Permission.CAMERA)
                                        || !XXPermissions.isGranted(WebViewDetailActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {

                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            XXPermissions.with(WebViewDetailActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
//                                             .permission(com.hjq.permissions.Permission.)//
                                                    .permission(com.hjq.permissions.Permission.CAMERA)//
                                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
                                                    .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(WebViewDetailActivity.this, permissions)));

                                                            takePhoto();

                                                        }
                                                    });

                                        }
                                    });

                                } else {
                                    takePhoto();
                                }


                            }

                        }
                    }
                }).show();

    }

    //选择图片
    private void takePhoto() {


        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);


    }

    //拍照
    private void takeCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

//        if (CommonUtil.hasSdcard()) {
        //这里可能需要检查文件夹是否存在
        //File file = new File(Environment.getExternalStorageDirectory() + "/APPNAME/");
        //if (!file.exists()) {
        //  file.mkdirs();
        //}

//        cameraFielPath = Environment.getExternalStorageDirectory() + "upload.jpg";
        //2023年10月24日10:42:25底下一行代码是我自己改造；
        cameraFielPath = PathUtils.getExternalAppFilesPath() + "upload.jpg";
        File outputImage = new File(cameraFielPath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputImage));
        startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
//        }

    }

//    /**
//     * 打开选择文件/相机
//     */
//    private void showFileChooser() {
//
////        Intent intent1 = new Intent(Intent.ACTION_PICK, null);
////        intent1.setDataAndType(
////                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
//        intent1.addCategory(Intent.CATEGORY_OPENABLE);
//        intent1.setType("*/*");
//
//        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        mCameraFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +
//                System.currentTimeMillis() + ".jpg";
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            // android7.0注意uri的获取方式改变
//            Uri photoOutputUri = FileProvider.getUriForFile(
//                    WebViewDetailActivity.this,
//                    BuildConfig.APPLICATION_ID + ".fileProvider",
//                    new File(mCameraFilePath));
//            intent2.putExtra(MediaStore.EXTRA_OUTPUT, photoOutputUri);
//        } else {
//            intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
//        }
//
//        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
//        chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
//        chooser.putExtra(Intent.EXTRA_INTENT, intent1);
//        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intent2});
//        startActivityForResult(chooser, REQUEST_CODE_FILE_CHOOSER);
//    }


    /**
     * webview没有选择文件也要传null，防止下次无法执行
     */
    private void clearUploadMessage() {

        if (uploadMessageAboveL != null) {
            uploadMessageAboveL.onReceiveValue(null);
            uploadMessageAboveL = null;
        }

        if (uploadMessage != null) {
            uploadMessage.onReceiveValue(null);
            uploadMessage = null;
        }

    }


    @Override
    protected int getContentViewId() {

        //2018年06月23日添加硬件加速代码
        //getWindow().setFormat(PixelFormat.TRANSLUCENT);
        //这个修复代码 可以暂时先放在这里
        //KeyboardUtils.fixAndroidBug5497(WebViewNormalActivity.this);
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        try {

            if (Integer.parseInt(Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,//
                                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);//
            }

        } catch (Exception e) {
            //retain
            e.printStackTrace();
        }

        return R.layout.activity_web_view_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        processExtraData();

        toolbarHandler = toolbarHelper;
        toolbarHelper.setTitle(titleName);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                checkWebBack();
            }
        });


        //如果是从政务服务和综合服务过来的需要添加"关闭"
        if (webViewFlag == ConstantApi.WHAT_TEXTSECRECYTURL
                || webViewFlag == ExtraValue.INDEXT_PATH_ORDER_LIST  //如果是【首页-商品订单-订单列表】-过来的
                || webViewFlag == ExtraValue.WEBVIEWFLAG_OPEN_NEW_ONE_WEBVIEW
                || webViewFlag == ExtraValue.WEBVIEWFLAG_HELPCENTER//设置页面-帮助中心
                || webViewFlag == ExtraValue.WEBVIEW_FLAG_COMPANY_ENTERPRISE//法大大企业认证
        ) {//如果是【隐私政策】过来的也要有叉号

            toolbarHelper.setLayoutClose(true, "", new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    KeyboardUtils.hideSoftInput(WebViewDetailActivity.this);

                    //关闭也添加一个判断。
                    /*if (TextUtils.equals(webViewFlagBackAccount, ConstantApi.ISJUMPFROMNOADDRESS)) {
                        //发送消息通知杀死【结算】界面
                        EventBus.getDefault().post(new EventBusAddressKill(ConstantApi.EVENTBUS_ADDRESSKILL));
                    } else if (TextUtils.equals(webViewFlagBackAccount, ConstantApi.ISJUMPFROMHASADDRESS)) {
                        //LogUtils.d("itchen---->因为关闭--发送通知结算刷新界面");
                        EventBus.getDefault().post(new EventBusAddressNotice(ConstantApi.EVENTBUS_ADDRESSNOTICE));
                    }*/

                    //这里应该关闭 所有堆栈之中的 详情页面：
                    //关闭堆栈之中指定的 WebViewNormalActivity 内容；
                    MianTaskManager.getInstance(WebViewDetailActivity.this).finishActivity(WebViewDetailActivity.this);

                    ActivityUtils.finishActivity(WebViewDetailActivity.this);

                }
            });

        } else {
            toolbarHelper.setLayoutClose(false, "", null);
        }

        if (webViewFlag == ConstantApi.VALUE_JUMPFROM_SUGGESTIONS_MAINPAGE) {//如果是投诉建议【意见反馈】过来的，

            //LogUtils.d("itchen---是投诉建议过来的");

            //投诉建议过来的，暂时也不要右上角的内容
            /*toolbarHelper.setLayoutRight(true, 4, "我的提交", new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    //点击 我的提交--到投诉建议的 ? 这里应该是
                    ActivityUtils.startActivity(SuggestionsListActivity.class);
                }
            });*/

            //2021年10月12日 的需求是 暂时屏蔽掉不要。
            toolbarHelper.setLayoutRight(false, 0, "", null);

        } else if (//如果是【首页-商品订单-订单列表】-过来的
                webViewFlag == ExtraValue.INDEXT_PATH_ORDER_LIST) {
            toolbarHelper.setLayoutRight(true, 1, getString(R.string.scanqr_code_str), new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    Bundle bundle = new Bundle();
//                    bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
                    bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST);
                    ActivityUtils.startActivity(bundle, MyBGAQRCodeActivity.class);
                }
            });

        } else {
            // || webViewFlag == ExtraValue.WEBVIEWFLAG_OPEN_NEW_ONE_WEBVIEW//如果是【首页-商品订单-订单列表-扫码核销详情】-过来的
            toolbarHelper.setLayoutRight(false, 0, "", null);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "onResume--onResume--onResume--onResume--onResume");

        mSession = Session.get(this);

        if (mWebView != null) {
            mWebView.onResume();
        }

        //标记是 打开了新的页面，然后

    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "---onNewIntent---onNewIntent---onNewIntent---onNewIntent---onNewIntent---onNewIntent");
//
//        setIntent(intent);
//
//        processExtraData();
//    }

    private void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            jumpFromFlag = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);
            //从别的界面跳转 过来的标题内容
//            isjumpfrom_hometop_title = bundle.getString(ExtraKey.ISJUMPFROM_HOMETOP_TITLE);

            titleName = bundle.getString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, "");

            webViewFlag = bundle.getInt(ExtraKey.EXTRA_WEBVIEW_FLAG);//携带的方式数字判断

//            if (jumpFromFlag == ExtraValue.WEBVIEWFLAG_HOMETOP_NOTICE) {//如果是首页过来的，那么需要取出id信息
//                noticeId_upLoad = bundle.getString(ExtraKey.EXTRA_WEBVIEW_NOTICEID);
//            }

        }


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        try {

            super.onConfigurationChanged(newConfig);

            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

            } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    float x = 0;
    float y = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        //通过wenview的touch来响应web上的图片点击事件
        //float density = getResources().getDisplayMetrics().density; //屏幕密度
        float density = ScreenUtils.getScreenDensity();//集成方法获取屏幕密度
        float touchX = event.getX() / density;  //必须除以屏幕密度
        float touchY = event.getY() / density;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            x = touchX;
            y = touchY;
        }

        if (event.getAction() == MotionEvent.ACTION_UP) {

            float dx = Math.abs(touchX - x);
            float dy = Math.abs(touchY - y);

            if (dx < 10.0 / density && dy < 10.0 / density) {

                //检测如果包含 什么URL标识 就不让点击 查看大图

                //LogUtils.d("itchen----onTouch--正在触摸 加载页面地址是---requestCurrentLoadPgeUrl---->" + requestCurrentLoadPgeUrl);
                //http://222.222.17.184:8881/auth/v1/product/getComboProductUrl

//                if (!TextUtils.isEmpty(requestCurrentLoadPgeUrl)) {
//
//                    if (TextUtils.equals(requestCurrentLoadPgeUrl, Constants.getInstance().getComboProductUrl())//
//                            || TextUtils.equals(requestCurrentLoadPgeUrl, Constants.getInstance().getComboOrderUrl())) {
//
//                        //LogUtils.d("itchen----onTouch----当前获取的界面地址是--requestCurrentLoadPgeUrl--->" + requestCurrentLoadPgeUrl);
//                        //http://222.222.17.184:8881/auth/v1/product/getComboProductUrl
//
//                        return false;//这里给消费掉，不让继续往下点击了
//                    }
//
//                }

                ViewUitls.clickImageInWebView(touchX, touchY, mWebView);

            }

        }

        return false;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInWebNomalQRCode(EventBusQRCode eventBusQRCode) {

        if (eventBusQRCode != null) {

            if (eventBusQRCode.getMessage() == ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST) {

                String qrCodeResult = eventBusQRCode.getContent();
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "接收到的扫码核销值为：-->" + qrCodeResult);

                if (!TextUtils.isEmpty(qrCodeResult)) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "qrCodeResult：-->" + qrCodeResult);

                    // TODO: 2023-08-20 17:11 数据截断，尽量让只发送一条数据；
                    method_gainData_by_qrCode_for_rice_ticked(qrCodeResult);

                } else {

                    if (TextUtils.isEmpty(qrCodeResult)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
                        mAlertView.show();
                    }

                }

            }
        }

    }

    //根据扫描的二维码信息，获取餐券的信息接口
    private void method_gainData_by_qrCode_for_rice_ticked(String _rqCode_content) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.code, _rqCode_content);
        //"code": "3edf8ce747464fb564de0989561e2dd24f3dd958"

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_DECODEORDERQRCODE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.decodeOrderQrCode_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .decodeOrderQrCode(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(WebViewDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String valueString) throws Throwable {

                        //获取完毕这个优惠券的信息之后，展示这个优惠券的信息；
                        if (valueString != null) {

                            //method_show_dist_dialog(_rqCode_content, couponCustomer);

                            //这里是扫码加载一个详情页；
//                            {
//                                    "code":"20000",
//                                    "data":"https://echelianhtml.ygxpt.com/order/detail?orderNo=2023081811364127908762&qrCode=33d08ce747464fb564de09885f1826d04a3ed854",
//                                    "message":"success"
//                            }

                            //重新打开一个详情页；
                            ViewUitls.method_toWebView_OpenNew(valueString, getString(R.string.title_order_detail));

                        } else {
                            ToastUtils.showShort(getString(R.string.action_abnormal));
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //
                    }
                });


    }

    @Override
    protected void onStop() {
        super.onStop();
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "itchen--->WebGoodDetaillActivity--onStop");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "itchen--->WebGoodDetaillActivity--onDestroy");

        //这里要清空本地记录的URL地址，不然其他页面传递 refreshflag   2是刷新 ，1是不管 的时候，也是打开 旧页面；
        //MMKV.defaultMMKV().encode(ConstantSign.MMKV_WEBVIEW_URL_TOP_URL, mWebView.getUrl());
        //清空本地数据；
        MMKV.defaultMMKV().removeValueForKey(ConstantSign.MMKV_WEBVIEW_URL_TOP_URL);

        loadError = false;//还原初始值内容。

        webViewFlag = 0;//release

        webViewFlagBack = "";//release

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }

        if (mSetting != null) {
            mSetting = null;
        }

        if (toolbarHandler != null) {
            toolbarHandler = null;
        }

        if (mRequest != null) {
            mRequest = null;
        }

        if (!ObjectUtils.isEmpty(handlerNomal)) {

            //这种在三农APP之中有报错，我去掉；
//            handlerNomal.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//
//                    // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
//                    // destory()
//                    ViewParent parent = mWebView.getParent();
//
//                    if (parent != null) {
//                        ((ViewGroup) parent).removeView(mWebView);
//                    }
//
//                    mWebView.stopLoading();
//                    mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
//                    // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
//                    mWebView.getSettings().setJavaScriptEnabled(false);
//                    mWebView.clearHistory();
//                    mWebView.clearView();
//                    mWebView.removeAllViews();
//
//                    mWebView.setVisibility(View.GONE);
//
//                    mWebView.destroy();
//
//                    mWebView = null;
//
//                    if (frameLayoutWebviewNomal != null) {
//                        frameLayoutWebviewNomal = null;
//                    }
//
//                    //LogUtils.d("itchen--->WebGoodDetaillActivity--webview的--doInBackground");
//
//                }
//            }, 1000);

            handlerNomal.removeCallbacksAndMessages(null);
        }

        if (frameLayoutWebViewDetail != null) {
            frameLayoutWebViewDetail = null;
        }

        if (progressView != null) {
            progressView = null;
        }

        if (mCircleProgressView != null) {
            mCircleProgressView = null;
        }

        if (frameLayoutWebViewDetail != null) {
            frameLayoutWebViewDetail.removeAllViews();
            //frameLayoutWebviewNomal = null;
        }

        // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
        // destory()
        ViewParent parent = mWebView.getParent();

        if (parent != null) {
            ((ViewGroup) parent).removeView(mWebView);
        }

        mWebView.stopLoading();
        mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错;
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.clearHistory();
        mWebView.clearView();
        mWebView.removeAllViews();

        mWebView.setVisibility(View.GONE);

        mWebView.destroy();

        mWebView = null;

        EventBus.getDefault().unregister(this);

        if (myJsApiListener != null) {
            myJsApiListener = null;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    public void onClickNodata(View v) {

        if (NetworkUtils.isConnected()) {//网络已连接则重试，未连接则提示打开设置界面

            findWebView();

            gainDatas();

        } else {

            //2018年01月24日亲测这种方式是可以的，可以应用到整个项目，再做封装吧
            /*new AlertView("标题", //
                    ConstantApi.NETWORKSETTING, //
                    "取消", //
                    new String[]{"确定"}, //
                    null, //
                    WebViewNormalActivity.this,//
                    AlertView.Style.Alert, //
                    new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {//
                            if (position == 0) {
                                NetworkUtils.openWirelessSettings();//
                            }
                        }
                    })//
                    .show();*/

        }

    }

    //测试地址"https://github.com/scwang90/SmartRefreshLayout
    /*private void testQRcode(String imageViewLoad){

        FutureTarget<Bitmap> fileFutureTarget = GlideApp.with(WebViewNormalActivity.this)
                .asBitmap()
                .load(imageViewLoad)
                .submit();

        //长按识别二维码测试
        Bitmap obmp = null;
        try {
            obmp = fileFutureTarget.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int width = obmp.getWidth();
        int height = obmp.getHeight();
        int[] data = new int[width * height];
        obmp.getPixels(data, 0, width, 0, 0, width, height);
        RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result re = null;
        try {
            re = reader.decode(bitmap1);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }

        if (re!=null) {
            LogUtils.d("itchen----第二种方式扫描的结果是--->" + re.getText());
        }else{
            LogUtils.d("itchen----第二种方式扫描的结果是--->不识别" );
        }

    }*/


    //顶部的进度条内容
    private ProgressView progressView;//进度条

    @Override
    public void initViews() {

        //先找到界面必用的+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        mCircleProgressView.setTextEnabled(true);
        mCircleProgressView.setStartAngle(45);
        mCircleProgressView.setProgress(10);//默认10个进度条

//        mWebView = new WebView(this);
        mWebView = new DWebView(this);

        //初始化进度条
        progressView = new ProgressView(WebViewDetailActivity.this);

        //自己手动修改
        final float scale = WebViewDetailActivity.this.getResources().getDisplayMetrics().density;
        //int reslut = (int) (dpValue * scale + 0.5f);
        int reslut = (int) (2 * scale + 0.5f);

        progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, reslut));

        //早期是一句话代码 后来拆分成上边的代码：因为如下一句是会报错的。
        //progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(2)));
        //progressView.setColor(ColorUtils.getColor(R.color.progresscol));

//        progressView.setColor(Color.parseColor("#31CE15"));
        progressView.setColor(ContextCompat.getColor(this, R.color.redcomm));

        progressView.setProgress(10);

        mWebView.addView(progressView);

        /*MaterialProgressBar materialProgressBar = new MaterialProgressBar(this);
        materialProgressBar.setVisibility(View.GONE);
        materialProgressBar.st
        materialProgressBar.setIndeterminate(true);*/

        //原始代码
        //mWebView = (com.tencent.smtt.sdk.WebView) findViewById(R.id.webView);
        //mWebView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        //LogUtils.d("itchen---WebViewNormalActivity---initViews");

        //加载页面
        //=================================================================================================
        //WebSettings webSetting = mWebView.getSettings();
        //mWebView.clearCache(true);

        //加载页面
        mWebView.requestFocus();//触摸焦点起作用

        //mWebView.setVerticalScrollBarEnabled(false);//取消Vertical ScrollBar显示
        //mWebView.setHorizontalScrollBarEnabled(false); //取消Horizontal ScrollBar显示

        //这段兼容视频代码要在初始化的时候加入

        try {

            if (mWebView.getX5WebViewExtension() != null) {

                mWebView.getX5WebViewExtension().setHorizontalScrollBarEnabled(false);//水平不显示滚动按钮
                mWebView.getX5WebViewExtension().setVerticalScrollBarEnabled(false); //垂直不显示滚动按钮

                //关于全屏播放之前的设置
                Bundle data = new Bundle();
                data.putBoolean("standardFullScreen", false);// true 表示标准全屏，会调起onShowCustomView()，false 表示X5全屏；不设置默认false，
                data.putBoolean("supportLiteWnd", false);// false ：关闭小窗；true：开启小窗；不设置默认true，
                data.putInt("DefaultVideoScreen", 2);// 1：以页面内开始播放，2：以全屏开始播放；不设置默认：1

                mWebView.getX5WebViewExtension().invokeMiscMethod("setVideoParams", data);

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        CommUtils.setWebViewX5(mWebView, 0);

        // : 2023-04-03 修改useragent
        String ua = mWebView.getSettings().getUserAgentString();
        //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "获取到的ua=>" + ua);
        mWebView.getSettings().setUserAgentString(ConstantSign.USER_AGENT_YGXSK + mWebView.getSettings().getUserAgentString());
        //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "添加前缀之后的内容 获取到的ua=>" + mWebView.getSettings().getUserAgentString());

        //交互暂时屏蔽。
        //mWebView.addJavascriptInterface(getHtmlObject(), "Android");
        //Message message = new Message();
        //mWebView.requestImageRef(message);

        //-----------------------------------------------------------------
        mWebView.addJavascriptObject(new JsApi(myJsApiListener), null);
        //mWebView.addJavascriptObject(new JsEchoApi(),"echo");
        //-----------------------------------------------------------------
        //做【查看大图】和【视频预览】，
        mWebView.addJavascriptInterface(new MJavascriptInterface(mActivityInstance, mActivityInstance), "imageClick");
        mWebView.addJavascriptInterface(new MJavascriptInterface(mActivityInstance, mActivityInstance, mWebView), "videoClick");
        mWebView.setOnTouchListener(this);
        //-----------------------------------------------------------------

        if (frameLayoutWebViewDetail != null) {

            frameLayoutWebViewDetail.setVerticalFadingEdgeEnabled(false);
            frameLayoutWebViewDetail.setVerticalScrollBarEnabled(false);
            frameLayoutWebViewDetail.setHorizontalScrollBarEnabled(false);

            frameLayoutWebViewDetail.addView(mWebView, new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT));
        }

        findWebView();

        /*IX5WebViewExtension extension = mWebView.getX5WebViewExtension();

        if (extension != null) {
            LogUtils.d("X5 core 集成成功-->" + QbSdk.getTbsVersion(WebViewNormalActivity.this));
        } else {
            LogUtils.d("Sys Core 未集成成功--");
        }*/
    }

//    //退出登录的接口
//    private void method_loginOut(String _message) {
//
//        if (!TextUtils.isEmpty(_message)) {
//            CommUtils.loginInfoOutLogicH5(WebViewNormalActivity.this, _message, MMKV.defaultMMKV().decodeString(ConstantSign.P_INPUTNAMELASTTIME));
//        } else {
//            CommUtils.loginInfoOutLogicH5(WebViewNormalActivity.this, getString(R.string.hasloginout), MMKV.defaultMMKV().decodeString(ConstantSign.P_INPUTNAMELASTTIME));
//        }
//
//    }


    @Override
    public void gainDatas() {

        if (NetworkUtils.isConnected()) {
            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "getServerDatas");
            getServerDatas();
        } else {
            netWorkError();
        }

    }

    private void getServerDatas() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            if (webViewFlag == ExtraValue.WEBVIEWFLAG_BULLETIN) {//社区动态这里不论哪个状态都是1

                //String noticeid = bundle.getString(ExtraKey.EXTRA_WEBVIEW_NOTICEID);

                //2019年10月17日原始的获取公告详情的代码
                HashMap<String, Object> map = new HashMap<>();
                //map.put(Parameterkey.communityId, mSession.getCommunityId());
                //map.put("shopInfoId", mSession.getShopInfoId());
                //map.put(Parameterkey.noticeId, noticeid);

                AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
                addLogUpLoadInfo.setActivity(mActivityInstance);
                addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GOTONOTICEPAGE);//请求数字标识
                addLogUpLoadInfo.setUrlPath(ApiService.getNoticeDetailWebPageUrl);//url地址
                addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
                addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
                addLogUpLoadInfo.setHashMapParameter(map);

                NetworkManager.getInstance().initRetrofitRxJava()
                        .create(ApiService.class)
                        .getNoticeDetailWebPage(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))//暂时为空
                        .compose(WebViewDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                        .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>(ConstantApi.IS_ACTIVITY_ITSELF, WebViewDetailActivity.this) {

                            @Override
                            public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                                super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            }

                        }))
                        .subscribe(new Consumer<String>() {

                            @Override
                            public void accept(String data) throws Exception {

                                //String data = response.succeed().getData();
                                if (!TextUtils.isEmpty(data)) {
                                    method_loadUrl(data);
                                } else {
                                    netWorkError();
                                    ToastUtils.showShort(ConstantSign.NET_BAD);
                                }

                            }

                        }, new ErrorConsumer() {

                            @Override
                            protected void error(ApiException e) {
                                //
                            }
                        });

            } else if (webViewFlag == ExtraValue.WEBVIEWFLAG_HOMETOP_NOTICE//如果是加载消息过来的；
                    || webViewFlag == ExtraValue.INDEXT_PATH_ORDER_LIST//是从首页的过来-商品订单-订单管理
                    || webViewFlag == ExtraValue.INDEXT_PATH_MEMBER_MANAGE//首页的会员管理
                    || webViewFlag == ExtraValue.WEBVIEWFLAG_OPEN_NEW_ONE_WEBVIEW//扫码核销的打开商品详情
                    || webViewFlag == ExtraValue.WEBVIEWFLAG_HELPCENTER//设置页-帮助中心
                    || webViewFlag == ExtraValue.WEBVIEW_FLAG_COMPANY_ENTERPRISE//法大大企业认证直接打开后给返回的url
            ) {//

                String extra_webview_loadurl = bundle.getString(ExtraKey.EXTRA_WEBVIEW_LOADURL);
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "携带的链接-->" + extra_webview_loadurl);

                //这里加载过来的都是 携带的外链内容
                sendMsg(handlerNomal, HANDLER_EXTRA_WEBVIEW_LOADURL, extra_webview_loadurl);

            } else if (webViewFlag == ConstantApi.WHAT_TEXTSECRECYTURL) {//如果是隐私政策过来的；

                //method_load(Constants.getInstance().secrecytUrl() + "?name=" + AppUtils.getAppName());
                sendMsg(handlerNomal, HANDLER_TEXTURL_PRIVACY_POLICY, ApiService.secrecytUrl + "?name=" + AppUtils.getAppName());

            } else if (webViewFlag == ExtraValue.WHAT_TEXTAGREEMENTURL) {//如果是用户协议过来的

                //method_load(Constants.getInstance().agreementPage() + "?name=" + AppUtils.getAppName());
                sendMsg(handlerNomal, HANDLER_TEXTURL_USER_AGREEMENT, ApiService.agreementPageUrl + "?name=" + AppUtils.getAppName());

            } else {

                String extra_webview_loadurl = bundle.getString(ExtraKey.EXTRA_WEBVIEW_LOADURL);
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "携带的链接-->" + extra_webview_loadurl);
                //这里加载过来的都是 携带的外链内容
                sendMsg(handlerNomal, HANDLER_EXTRA_WEBVIEW_LOADURL, extra_webview_loadurl);
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "bundle是空值");
            }
        }

    }

    private void method_loadUrl(String h5url) {
        sendMsg(handlerNomal, HANDLER_NOMAL_FLAG, h5url);
    }


    private void checkWebBack() {

        //软键盘关闭-因为H5页面调用软键盘
        if (KeyboardUtils.isSoftInputVisible(WebViewDetailActivity.this)) {
            KeyboardUtils.hideSoftInput(WebViewDetailActivity.this);
        }

        methodBack();

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            method_title();

//            CommUtils.checkDialog(mAlertView);

            if (mWebView != null && mWebView.canGoBack()) {

                mWebView.goBack();

                return true;

            } else {
                //消息推送的跳转内容--原始逻辑
                //2018年04月16日逻辑。
                checkWebBack();

            }

        }

        return super.onKeyDown(keyCode, event);
    }

    private void method_title() {
        //返回标题内容,每点击一次就清空一次最后一条记录
        if (mWebView != null) {
            WebBackForwardList list = mWebView.copyBackForwardList();
            if (list != null) {
                WebHistoryItem item = list.getCurrentItem();
                if (item != null) {
                    if (toolbarHandler != null) {
                        toolbarHandler.setTitle(item.getTitle());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "标题内容--method_title-->" + item.getTitle());
                    }
                }
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (null == uploadMessage && null == uploadMessageAboveL) return;
        if (resultCode != RESULT_OK) {//同上所说需要回调onReceiveValue方法防止下次无法响应js方法
            if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
            return;
        }

        Uri result = null;
        if (requestCode == FILE_CAMERA_RESULT_CODE) {
            if (null != data && null != data.getData()) {
                result = data.getData();
            }
            if (result == null && hasFile(cameraFielPath)) {
                result = Uri.fromFile(new File(cameraFielPath));
            }
            if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(new Uri[]{result});
                uploadMessageAboveL = null;
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (data != null) {
                result = data.getData();
            }
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }

    }

    /**
     * 判断文件是否存在
     */
    public static boolean hasFile(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(Intent intent) {
        Uri[] results = null;
        if (intent != null) {
            String dataString = intent.getDataString();
            ClipData clipData = intent.getClipData();
            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }
            if (dataString != null)
                results = new Uri[]{Uri.parse(dataString)};
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public void methodBack() {

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--methodBack--methodBack--methodBack--methodBack");

        //2018年05月中间发现调用钱包的时候这里有软键盘弹出退出的时候没有关闭---只有在钱包的时候用到。
        if (KeyboardUtils.isSoftInputVisible(WebViewDetailActivity.this)) {
            //那么关闭之
            KeyboardUtils.hideSoftInput(WebViewDetailActivity.this);
        }
        //==============================================================================

        //这个有点特殊需要跳转的内容
        if (mWebView != null) {

            method_title();

            if (mWebView.canGoBack()) {

                //返回标题内容
//                if (titleLists != null && !titleLists.isEmpty()) {
//                    titleLists.remove(titleLists.size() - 1);
//                }

                mWebView.goBack();

            } else {

                //2019年03月29日 添加
//                checkFinish();
                ActivityUtils.finishActivity(WebViewDetailActivity.this);
            }

        } else {

            //checkFinish();
            ActivityUtils.finishActivity(WebViewDetailActivity.this);
        }
    }
}
